#!/bin/sh

#Copyright (c) 2014 Luigi Tarenga <luigi.tarenga@gmail.com>
#Distributed under the terms of a MIT license.

cd ${0%/*}

case "$1" in
 first-boot)
   if [ -d temp/master_lockdir ] ; then
      echo temp/master_lock is locked. cannot initialize state-machine.
      exit 1
   fi

   echo first-boot

   #set the preferred sh interpreter
   for f in lite-raft-* internals/* ; do
      #some sed don't support -i
      sed -e "s|^#!.*|#!${2:-/bin/sh}|" < $f > temp123
      chmod +x temp123
      mv temp123 $f
   done

   rm -rf   state state-machine-log   state-machine-data state-machine-snapshot
   mkdir -p state state-machine-log/0 state-machine-data state-machine-snapshot

   echo "" > state-machine-log/0/0
   echo 0  > state/current_term
   echo 0  > state/last_log_index
   echo "" > state/voted_for
   nohup ./lite-raft-server > message-log/lite-raft-server.log 2>&1 < /dev/null &
 ;;

 start)
   if [ -d temp/master_lockdir ] ; then
      echo temp/master_lock is locked. server already started.
      exit 1
   fi
   echo start
   nohup ./lite-raft-server > message-log/lite-raft-server.log 2>&1 < /dev/null &
 ;;

 stop)
   echo stop
   shell_cmd=$(head -1 lite-raft-server)
   shell_cmd=${shell_cmd#\#!}
   pkill -x -f "$shell_cmd ./lite-raft-server"
 ;;

 *)
   echo "Usage: ${0##*/} { first-boot [ shell ] | start | stop }"
   echo "  Main script to start and stop lite-raft service or initialize"
   echo "  lite-raft state machine data and logs."
   echo "      start   start lite-raft-server. preserve data and log"
   echo "       stop   stop lite-raft-server and child processes."
   echo " first-boot   cancel information in the local state machine data and"
   echo "              logs and start lite-raft-server. Execute this command"
   echo "              on every node where you want to cancel every data."
   echo "              you can specify which posix shell to use for every script."
 ;;
esac
